#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <QNetworkInterface>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QHostAddress address = QHostAddress(QHostAddress::LocalHost);
    QString strIPAddress = address.toString();
    ui->label->setText(strIPAddress);
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list) {
        // 主机地址为空
        if (address.isNull())
            continue;

        qDebug() << "********************";
        QAbstractSocket::NetworkLayerProtocol nProtocol = address.protocol();
        QString strScopeId = address.scopeId();
        QString strAddress = address.toString();
        bool bLoopback = address.isLoopback();

        // 如果是IPv4
        if (nProtocol == QAbstractSocket::IPv4Protocol) {
            bool bOk = false;
            quint32 nIPV4 = address.toIPv4Address(&bOk);
            if (bOk)
                qDebug() << "IPV4 : " << nIPV4;
        }
        // 如果是IPv6
        else if (nProtocol == QAbstractSocket::IPv6Protocol) {
            QStringList IPV6List("");
            Q_IPV6ADDR IPV6 = address.toIPv6Address();
            for (int i = 0; i < 16; ++i) {
                quint8 nC = IPV6[i];
                IPV6List << QString::number(nC);
            }
            qDebug() << "IPV6 : " << IPV6List.join(" ");
        }
        QString tmpstr;
        tmpstr = "Protocol : " ;
        tmpstr.append(nProtocol);
        tmpstr.append("\n");
        ui->label->setText(tmpstr);

        qDebug() << "Protocol : " << nProtocol;
        qDebug() << "ScopeId : " << strScopeId;
        qDebug() << "Address : " << strAddress;
        qDebug() << "IsLoopback  : " << bLoopback;
    }
}
